package dating.service;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import dating.model.Message;
import dating.model.User;

/**
 * Session Bean implementation class MessageService
 */
@Stateless
public class MessageService extends GenericService<Message, Long> implements MessageServiceLocal {
	
	@PersistenceContext
	EntityManager em;
	
    /**
     * Default constructor. 
     */
    public MessageService() {
    	super(Message.class);
    }

	@Override
	public void sendMessage(String messageBody, User sender, User recepient) {
		Message msg = new Message();
		msg.setMessage(messageBody);
		msg.setSender(sender);
		msg.setRecepient(recepient);
		msg.setRead(false);
		this.em.merge(msg);
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Message> findAllByUserId(long userId) {
		Query query = this.em.createQuery("from " + entityClass.getName() + " m where m.sender  ='" + userId + "' OR m.recepient ='" + userId + "'");
		List<Message> result = query.getResultList();
	    if (result.isEmpty()) return null;
	    else return result;
	}

}
